<template>
  <div class="upload-file">
    <el-upload
      multiple
      action
      :class="{ hide: hideUpload_introduce }"
      :list-type="uploadType"
      :before-upload="handleBeforeUpload"
      :file-list="fileList"
      :limit="limit"
      :on-exceed="handleExceed"
      :on-remove="handleDelete"
      :on-change="handleIntroduceUploadHide"
      :show-file-list="true"
      class="upload-file-uploader"
      ref="upload"
      :on-preview="handlePictureCardPreview"
    >
      <i v-if="uploadType != 'text'" class="el-icon-upload"></i>
      <el-button
        :loading="loading"
        v-if="uploadType == 'text'"
        type="success"
        size="mini"
        >点击上传
      </el-button>
      <div class="el-upload__tip" slot="tip" v-if="showTip">
        请上传
        <template v-if="fileSize">
          大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
        </template>
        <template v-if="fileType">
          格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
        </template>
        的文件
      </div>

      <el-dialog
        :visible.sync="dialogVisible"
        title="预览"
        width="800"
        append-to-body
      >
        <img
          v-if="uploadType != 'text'"
          :src="dialogImageUrl"
          style="display: block; max-width: 100%; margin: 0 auto"
        />
        <div v-else>
          <a target="_blank" :href="dialogImageUrl">{{ dialogImageUrl }} </a>
        </div>
      </el-dialog>
    </el-upload>
  </div>
</template>
<script>
import { getRandomString } from "../utils/util";

//obs华为云包
import ObsClient from "esdk-obs-browserjs/src/obs";

//图片压缩工具
import * as imageConversion from "image-conversion";

import {
  accessKeyId,
  secretAccessKey,
  obsServer,
  imgUrl,
  bucketName
} from "../../config/prod.env";

export default {
  name: "FileUpload",
  props: {
    // 值
    value: [String, Object, Array],
    // 数量限制
    limit: {
      type: Number,
      default: 999
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 50
    },
    // 上传的类型
    uploadType: {
      typeof: String,
      default: () => "picture-card"
    },

    fileType: {
      type: Array,
      default: () => ["jpeg", "png", "jpg"]
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    },
    //是否为上传首页图片
    isHomeImg: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      number: 0,
      uploadList: [],
      headers: {
        "Content-Type": "multipart/form-data"
      },
      fileList: [],
      dialogVisible: false,
      hideUpload_introduce: false,
      dialogImageUrl: "",
      file: undefined,
      loading: false
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          let temp = 1;
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : this.value.split(",");
          // 然后将数组转为对象数组
          this.fileList = list.map(item => {
            if (typeof item === "string") {
              item = { name: item, url: item };
            }
            item.uid = item.uid || new Date().getTime() + temp++;
            return item;
          });
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    }
  },
  mounted() {
    if (this.limit == 1) {
      this.hideUpload_introduce = true;
    }
  },
  methods: {
    handleIntroduceUploadHide(file, fileList) {
      if (this.limit == 1) {
        this.hideUpload_introduce = true;
      }
    },

    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      this.loading = true;
      let isText = this.uploadType == "text" ? true : false;
      console.log("file", file);
      let that = this;
      // 校检文件类型
      if (this.fileType) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        const isTypeOk = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
        if (!isTypeOk) {
          this.$message.error(
            `文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`
          );
          return false;
        }
      }
      // 校检文件大小
      // if (this.fileSize) {
      //   const isLt = file.size / 1024 / 1024 < this.fileSize;
      //   if (!isLt) {
      //     this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
      //     return false;
      //   }
      // }

      // 上传时 图片大于1M就会进行一个自动压缩到500k的操作
      const sizes = file.size / 1024 / 1024 < 1;

      // 图片压缩
      let a = new Promise(resolve => {
        if (!sizes) {
          // 上传数据手册和检测报告
          if (isText) {
            //上传的数据手册类型不压缩
            console.log("上传的数据手册类型不压缩");
            resolve(file);
          } else {
            // 压缩到500KB,这里的500就是要压缩的大小,可自定义
            imageConversion.compressAccurately(file, 500).then(res => {
              resolve(res);
            });
          }
        } else {
          resolve(file);
        }
      });
      console.log("压缩图片",a);
      let names = file.name.split(".");
      // 图片的后缀名字 随机字符串 + 当前时间戳 + 截取的文件类型
      let uuids =
        getRandomString(8) + Date.now() + "." + names[names.length - 1];
      // 创建ObsClient实例
      let homeg = "pccshomeimage.jpg"; // 这是首页图片上传固定的图片路径
      a.then(res => {
        var obsClient = new ObsClient({
          access_key_id: accessKeyId, // 你的ak
          secret_access_key: secretAccessKey, // 你的sk
          server: obsServer // 你的endPoint  记得加入https://
        });
        //'\u00A0'空格转为普通空格
        let replaceStrName = file.name.replace(RegExp("\u00A0", "g"), " ");
        replaceStrName = file.name.replace("+", "%2B");
        console.log(replaceStrName);
        obsClient.putObject(
          {
            Bucket: bucketName, // 桶名
            Key: that.isHomeImg ? homeg : isText ? replaceStrName : uuids, // 文件名   如果是上传首页图片就用固定的路径，如果是上传数据手册，数据报告是用图片文件图片本身的名字，如果是上传图片，那就是根据生成规则随机生成文件名。
            SourceFile: res //流文件
          },
          function(err, result) {
            if (err) {
              that.handleUploadError();
            } else {
              //上传数据手册 数据报告
              if (isText) {
                that.uploadList = {
                  name: `${replaceStrName}`,
                  url: `${imgUrl}${replaceStrName}` // 因为访问路径OBS没有给你返回需要自行拼接   拼接格式： https:// +  桶名 + endPoint  +  /  + 上传的文件路径
                };
              } else {
                that.uploadList = {
                  name: `${uuids}`,
                  url: `${imgUrl}${
                    that.isHomeImg ? homeg : uuids // 如果是首页图片上传就是用每次上传图片都用同一个路径
                  }?v=${new Date().getTime()}` // 这里加上时间戳是解决相同地址的情况下图片更新延迟的问题
                };
              }
              that.fileList = that.fileList.concat(that.uploadList);

              that.uploadList = {};
              that.number = 0;
              that.$emit("input", that.fileList);
              that.loading = false;
            }
          }
        );
        this.number++;
        return true;
      });
    },
    // 文件个数超出
    handleExceed() {
      this.$message.error(`上传图片数量不能超过 ${this.limit} 张!`);
    },
    // 上传失败
    handleUploadError(err) {
      console.log(err);
      this.$message.error("上传图片失败，请重试");
    },

    // 预览
    handlePictureCardPreview(file) {
      if (this.uploadType == "text") {
        window.open(file.url, "_blank");
      } else {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      }
    },

    // 删除文件
    handleDelete(file, fileList) {
      console.log(fileList, this.limit);
      if (fileList.length == 0) {
        this.hideUpload_introduce = false;
      }
      this.fileList = fileList
      this.$emit("input", this.fileList);
      // const findex = this.fileList.map(f => f.name).indexOf(file.name);
      // if (findex > -1) {
      //   this.fileList.splice(findex, 1);
      //   this.$emit("input", this.fileList);
      // }
      this.$forceUpdate();
    }
  }
};
</script>

<style lang="less" scoped>
.upload-file-uploader {
  margin-bottom: -10px;
}
/deep/ .upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
  transition: none !important;
}
/deep/ .upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
  transition: none !important;
}
.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}

/deep/.hide .el-upload--picture-card {
  display: none;
}

/deep/ .el-upload-list__item {
  transition: none !important;
  /* display: none !important; */
}

/* 推荐，实现简单 */
/deep/ .el-upload-list__item.is-ready,
.el-upload-list__item.is-uploading {
  display: none !important;
  transition: none !important;
}

// /deep/ .el-upload--picture-card {
//   width: 100px;
//   height: 100px;
// }
// /deep/ .el-upload {
//   width: 120px;
//   height: 120px;
//   line-height: 120px;
// }
// /deep/ .el-upload-list--picture-card .el-upload-list__item {
//   width: 120px;
//   height: 120px;
// }
// /deep/ .el-upload-list--picture-card .el-upload-list__item-thumbnail {
//   width: 120px;
//   height: 120px;
//   line-height: 120px;
// }
</style>
